package com.alibaba.incubator.loadtestermini.model.behavior.organism;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;

import com.alibaba.incubator.loadtestermini.model.measurement.recorder.SceneRecorder;

/**
 * (created at 2010-5-27)
 * 
 * @author <a href="mailto:shuo.qius@alibaba-inc.com">QIU Shuo</a>
 */
public class Scenario implements InitializingBean {
    private static final Logger logger = LoggerFactory.getLogger(Scenario.class);

    private String resultRootPath;
    private List<Scene> scenes;

    public void setScenes(List<Scene> scenes) {
        this.scenes = scenes;
    }

    public void setResultRootPath(String resultRootPath) {
        this.resultRootPath = resultRootPath;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (resultRootPath == null) {
            throw new IllegalArgumentException("property of 'resultRootPath' is null!");
        }
        if (scenes == null || scenes.size() <= 0) {
            throw new IllegalArgumentException("property of 'scenes' is null or empty!");
        }
    }

    public final void execute() {
        try {
            for (Scene scene : scenes) {
                try {
                    scene.startup(resultRootPath);
                    scene.execute();
                } catch (InterruptedException ie) {
                    logger.warn("resultRootPath", ie);
                } catch (Exception re) {
                    logger.error(scene.getName(), re);
                } finally {
                    scene.shutdown();
                }
            }
        } catch (RuntimeException e) {
            logger.error("resultRootPath=" + resultRootPath, e);
        } finally {
            shutdown();
        }
    }

    protected void shutdown() {
        /** do nothing */
    }
}
